package com.example.site.controller.file;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.util.SaResult;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Instant;

@RestController
@RequestMapping("/api/upload")
public class FileController {
    @Value("${file.upload.dir}")
    private String uploadDir;

    @SaCheckLogin
    @PostMapping("/upload")
    public SaResult handleFileUpload(@RequestParam("file") MultipartFile file) {
        try {
            // 获取上传文件名
            String originalFilename = file.getOriginalFilename();
            // 生成新文件名（时间戳 + 扩展名）
            String newFilename = Instant.now().getEpochSecond() + originalFilename.substring(originalFilename.lastIndexOf("."));
            // 使用 Apache Commons IO 处理文件上传
            FileUtils.writeByteArrayToFile(new File(uploadDir, newFilename), file.getBytes());
            return SaResult.data(newFilename);
        } catch (IOException e) {
            e.printStackTrace();
            return SaResult.error(e.getMessage());
        }
    }

    @GetMapping("/image/{imageName:.+}")
    public void getImage(@PathVariable String imageName, HttpServletResponse response) throws IOException {
        File image = new File(uploadDir, imageName);
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        IOUtils.copy(new FileInputStream(image), response.getOutputStream());
    }
}
